package com.socket.nio.server;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @auther zhangwj
 * @date 2020/6/14 11:26 上午
 */
public class DemoServer {

    private volatile boolean flag = true;

    public void socketDemo(int port) {
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            Socket socket = null;
            InputStream inputStream = null;
            while (flag) {
                socket = serverSocket.accept();
                inputStream = socket.getInputStream();
                InputStream finalInputStream = inputStream;
                new Thread(() -> {
                    try {
                        handle(finalInputStream);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }).start();
            }
            if (null != socket) {
                socket.close();
            }
            serverSocket.close();
        } catch (IOException e) {
        }
    }

    private void handle(InputStream inputStream) throws InterruptedException, IOException {
        if (null != inputStream) {
            byte[] bytes = new byte[1024];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = inputStream.read(bytes)) != -1) {
                //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
                sb.append(new String(bytes, 0, len, "UTF-8"));
            }
            System.out.println("get message from client: " + sb.toString());
            if (null != sb.toString() && sb.toString().equals("9999")) {
                flag = false;
            }
            if (null != inputStream) {
                inputStream.close();
            }
        }
    }

    public static void main(String[] args) {
        DemoServer demoServer = new DemoServer();
        demoServer.socketDemo(8080);
    }
}
